package com.shangyueshang.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.shangyueshang.common.SysConstants;
import com.shangyueshang.model.SysDict;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.service.SysDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/26 12:43
 * @version: v1.0.0
 *
 * <p>七牛云上传文件工具类</p>
 */
@Slf4j
@Component
public class QiNiuCloudUtil {

    /**
     * 设置需要操作的账号的AK和SK
     */
    private String ACCESS_KEY;
    private String SECRET_KEY;
    /**
     * 七牛云域名
     */
    private String DOMAIN;
    /**
     * 要上传的空间
     */
    private String BUCKET_NAME;
    /**
     * 密钥
     */
    private Auth AUTH;

    @Resource
    private SysDictService sysDictService;

    @PostConstruct
    public void init() {
        List<SysDict> list = sysDictService.findByType(SysConstants.qiniu_cloud);
        Map<String, String> map = list.stream().collect(Collectors.toMap(SysDict::getLabel, SysDict::getValue));
        ACCESS_KEY = map.get(SysConstants.qiniu_access_key);
        SECRET_KEY = map.get(SysConstants.qiniu_secret_key);
        DOMAIN = map.get(SysConstants.qiniu_domain);
        BUCKET_NAME = map.get(SysConstants.public_bucket);
        AUTH = Auth.create(ACCESS_KEY, SECRET_KEY);
    }

    private String getUpToken() {
        return AUTH.uploadToken(BUCKET_NAME, null, 3600, new StringMap().put("insertOnly", 1));
    }

    /**
     * 普通上传
     *
     * @param filePath
     * @param fileName
     * @return
     */
    public String upload(String filePath, String fileName) {
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        // 创建上传对象
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            // 调用put方法上传
            Response res = uploadManager.put(filePath, fileName, getUpToken());
            // 打印返回的信息
            System.out.println(res.bodyString());
            if (res.isOK()) {
                Ret ret = res.jsonToObject(Ret.class);
                //如果不需要对图片进行样式处理，则使用以下方式即可
                return DOMAIN + ret.key;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                // ignore
            }
        }
        return null;
    }

    /**
     * base64上传文件
     *
     * @param base64
     * @param key
     * @return
     */
    public HttpResult upload(byte[] base64, String key) {
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        // 创建上传对象
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            Response res = uploadManager.put(base64, key, getUpToken());
            if (res.isOK()) {
                //如果不需要对图片进行样式处理，则使用以下方式即可
                return HttpResult.ok(DOMAIN + key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return HttpResult.fail("上传文件失败");
    }

    /**
     * 普通删除
     *
     * @param fileUrl
     */
    public HttpResult delete(String fileUrl) {
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        // 实例化一个BucketManager对象
        BucketManager bucketManager = new BucketManager(AUTH, cfg);
        // key就是图片在七牛云的名称
        String key = fileUrl.substring(fileUrl.indexOf("com") + "com/".length());
        try {
            // 调用delete方法移动文件
            Response response = bucketManager.delete(BUCKET_NAME, key);
            return response.isOK() ? HttpResult.ok() : HttpResult.fail("删除失败");
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return HttpResult.fail("删除文件失败");
    }

    class Ret {
        public long fsize;
        public String key;
        public String hash;
        public int width;
        public int height;
    }
}
